package de.hwrberlin.remo.logging;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Layout;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LoggingEvent;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;

public class ConsoleViewAppender extends AppenderSkeleton {

	private MessageStylingBuilder stylingBuilder = new MessageStylingBuilder();
	private StyledText styledText;
	
	public ConsoleViewAppender(StyledText styledText) {
		this.styledText = styledText;
		setLayout(new PatternLayout("[%-5p] - %d{HH:mm:ss.SSS} - %c{1}: %m%n"));
	}
	
	@Override
	public void close() {}

	@Override
	public boolean requiresLayout() {
		return true;
	}

	@Override
	protected void append(final LoggingEvent evt) {
		if(styledText != null && !styledText.isDisposed()) {
			styledText.getDisplay().asyncExec(new Runnable() {
				
				@Override
				public void run() {
					String message = getLayout().format(evt);
					StyleRange style = stylingBuilder.buildStyleForMessage(message);
					
					int messageStart = styledText.getCharCount();
					
					styledText.append(message);
					
					if(style != null) {
						style.start = messageStart;
						styledText.setStyleRange(style);
					}
					
					styledText.setSelection(styledText.getCharCount());
				}
			});
		}
	}
	
	@Override
	public Layout getLayout() {
		return super.getLayout();
	}

	/////////////////////
	/* Getter / Setter */
	
	public StyledText getStyledText() {
		return styledText;
	}

	public void setStyledText(StyledText styledText) {
		this.styledText = styledText;
	}
}